package com.ag.oa.core.controller;


import com.ag.oa.core.dao.IQuestionDao;
import com.ag.oa.core.entity.dto.QuestionDto;
import com.ag.oa.core.entity.vo.QAUserVO;
import com.ag.oa.core.entity.vo.QuestionVO;
import com.ag.oa.core.entity.vo.SelectionVO;
import com.ag.oa.core.service.IQAUserService;
import com.ag.oa.core.service.IQuestionService;
import com.ag.oa.core.service.ISelectionService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping({"/Question"})
public class QuestionController {

    @Autowired
    private IQuestionService questionService;

    @Autowired
    private ISelectionService selectionService;

    @Autowired
    private IQAUserService qaUserService;

    private static final Logger logger = LoggerFactory.getLogger(QuestionController.class);

    @RequestMapping(value = "/getOne", produces = "text/json;charset=UTF-8")
    public @ResponseBody
    String getQuestionData(String userId) {

        JSONObject res = new JSONObject();
        int code = 200;
        try {
//            List<QuestionVO> voList   = questionService.getOneQuestionRandom();
            QuestionVO questionVO = questionService.getOneQuestionRandomLy();
            System.out.println("questionVO");
            System.out.println(questionVO);
            String currentQuesId = questionVO.getQuesId();
            List<SelectionVO> selectionByQuesId = selectionService.getSelectionByQuesId(currentQuesId);
            QAUserVO userVOS = qaUserService.getUserQuesIndex(userId);
            System.out.println(selectionByQuesId);
            Integer userQuesIndex = userVOS.getQuesIndex();
            if(userQuesIndex>9){
                res.put("userQuesIndex", userQuesIndex);
                res.put("questionData", "[]");
                res.put("selectionData", "[]");
            }else{
                res.put("userQuesIndex", userQuesIndex);
                res.put("questionData", questionVO);
                res.put("selectionData", selectionByQuesId);
            }
        } catch (Exception e) {
            e.printStackTrace();
            code = 500;
            logger.error(e.getMessage());
        }

        res.put("resCode", code);
        return res.toJSONString();
    }

    @PostMapping("/addone")
    public @ResponseBody
    String addQuestionData(@RequestBody QuestionDto questionDto) {
        JSONObject res = new JSONObject();
        System.out.println(questionDto);
        System.out.println(questionDto.getScore());
        System.out.println(questionDto.getSelectionVOList());
        String uuid = UUID.randomUUID().toString();
        //String id,String uploader,String source,Integer type,Integer score,String content
        questionService.addOneQuestion(
                uuid,
                questionDto.getUploader(),
                questionDto.getSource(),
                questionDto.getType(),
                questionDto.getScore(),
                questionDto.getContent()
        );


        List<SelectionVO> selectionVOList = new ArrayList<>();
        for (int i = 0; i < questionDto.getSelectionVOList().size(); i++) {
            String seluuid = UUID.randomUUID().toString();
            SelectionVO selElement = questionDto.getSelectionVOList().get(i);
            selElement.setQuestionId(uuid);
            selectionVOList.add(selElement);
            selectionService.addSelectionWithQuesId(
                    seluuid,
                    uuid,
                    selElement.getSelText(),
                    selElement.getIsRight()
            );
        }

        res.put("resCode", "200");
        return res.toJSONString();
    }

    @PostMapping("/answer")
    public @ResponseBody
    String answerTheQuestion(@RequestBody String reqString) {
//        ,List<String> answerIds
        JSONObject res = new JSONObject();

        JSONObject reqObject = JSON.parseObject(reqString);

        System.out.println(reqObject.getString("userId"));
        System.out.println(reqObject.getString("questionId"));
        System.out.println(reqObject.getString("answerIds"));

        String userId = reqObject.getString("userId");
        String questionId = reqObject.getString("questionId");
        String ansIdsStr = reqObject.getString("answerIds");

        String[] ansIdsArr = ansIdsStr.substring(1, ansIdsStr.length() - 1).split(",");
        for (int i = 0; i < ansIdsArr.length; i++) {
            System.out.println(ansIdsArr[i]);
        }

        List<String> answerIds = Arrays.asList(ansIdsArr);
        List<SelectionVO> selectionVOList = selectionService.getSelectionByQuesId(questionId);

        String quesResult = "0";

        List<String> rightArr = new ArrayList<>();
        List<String> rightArrId = new ArrayList<>();

        if (answerIds.size() == 0) {
            quesResult = "0";
        } else {
            System.out.println("answerids: " + answerIds);
            quesResult = "1";

            int rightCount = 0;

            for (int i = 0; i < selectionVOList.size(); i++) {
                SelectionVO s = (SelectionVO) selectionVOList.get(i);

                System.out.println(s.getSelId());
                System.out.println(s.getSelText());

                System.out.println(s.getIsRight());
                if (s.getIsRight() == 1) {
                    rightArr.add(s.getSelText());
                    rightArrId.add(s.getSelId());
                    rightCount++;
                }

                if (answerIds.contains(s.getSelId())) {
                    System.out.println("answerids contains this selid");
                    System.out.println(s.getIsRight());
                    if (s.getIsRight() == 0) {
                        quesResult = "0";
                    }
                }
            }

            System.out.println("rightCount" + rightCount);

            if (answerIds.size() != rightCount) {
                quesResult = "0";
            }


        }

        /*答题者完成题目的索引加1*/
        System.out.println("reqUserId" + userId);
        QAUserVO currentUser = qaUserService.getUserById(userId);
        System.out.println("currentUser" + currentUser);
        int currentIndex = currentUser.getQuesIndex();
        currentIndex = currentIndex + 1;
        qaUserService.modUserQuesIndex(userId, currentIndex);
        res.put("rightAnswer", rightArr);
        res.put("rightAnswerId", rightArrId);
        res.put("quesResult", quesResult);

        res.put("resCode", "200");
        return res.toJSONString();
//        return null;
    }

    @GetMapping("/suibian")
    public String suibian() {
        return "suibian";
    }
}
